package com.first.orange.controller;

import com.first.orange.beans.*;
import com.first.orange.service.PersonService;
import com.first.orange.service.impl.PersonServiceImpl;
import com.first.orange.util.EncodeUtils;
import com.sun.org.apache.xpath.internal.operations.Bool;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created on 2021/7/5.
 * <p>
 * Author : Lcywings
 * <p>
 * Description :
 */
@Controller
public class PersonCenterController {

    @Autowired
    PersonService personService;

    //用户id
    private Integer userId;

    /**
     * @author : Lcywings
     * @date : 2021/7/12 14:24
     * @acl : true
     * @description : 进入个人中心校验
     */
    public Boolean verify(HttpSession session) {
        //判断用户是否登录
        if (null == session.getAttribute("user") || "".equals(session.getAttribute("user"))) {
            return true;
        }
        //如果成功登录，判断用户是否为新用户
        UserLogin userLogin = (UserLogin) session.getAttribute("user");
        //如果是新用户，默认为用户添置初始信息
        if (null == personService.queryUserInfoByUserId(userLogin.getUserId())) {
            personService.insertInitUserByUserId(userLogin.getUserId(), userLogin.getPhone());
        }
        //添加全局用户id
        userId = userLogin.getUserId();
        return false;
    }


    /**
     * @author : Lcywings
     * @date : 2021/7/5 12:27
     * @acl : true
     * @description : 个人中心首页，获取个人资产数据&订单&收藏&足迹
     */
    @RequestMapping(value = "/personCenter", method = RequestMethod.GET)
    public String getPersonalAssets(Map<String, Object> map, HttpSession session) throws Exception {
        if (verify(session)) {
            return "redirect:/doLogin";
        }
        //个人资产
        //获取用户信息
        UserInformation userInformation = (UserInformation) personService.getPersonalAssets(userId).get("userInformation");
        map.put("userInformation", userInformation);
        // 获取账户余额
        map.put("accountBalance", userInformation.getAccountBalance());
        // 获取账户总积分
        map.put("totalPoints", userInformation.getTotalPoints());
        // 获取账户昵称
        map.put("nickName", userInformation.getNickName());
        // 获取账户优惠券数量
        map.put("couponTotal", personService.getPersonalAssets(userId).get("couponTotal"));


        //我的订单
        //获取订单详情
        List<OrderList> orderListsSort = personService.selectOrdersByUserId(userId);
        List<Orders> ordersList = new ArrayList<>();
        int count;
        if (orderListsSort.size() > 2)
            count = 2;
        else
            count = orderListsSort.size();
        for (int i = 0; i < count; i++) {
            ordersList.add(orderListsSort.get(i).getOrder().get(0));
        }
        map.put("orders", ordersList);
        return "person/index";
    }


    /**
     * @author : Lcywings
     * @date : 2021/7/6 8:38
     * @acl : true
     * @description : 去往个人信息页面
     */
    @RequestMapping(value = "/toInformation", method = RequestMethod.GET)
    public String toInformation(Map<String, Object> map) {
        //获取用户信息
        UserInformation userInformation = (UserInformation) personService.getPersonalAssets(userId).get("userInformation");

        //分隔日期
        Date date = userInformation.getBirthday();
        String year = new SimpleDateFormat("yyyy").format(date);
        String month = new SimpleDateFormat("MM").format(date);
        String day = new SimpleDateFormat("dd").format(date);
        //分别装入map中方便前端显示
        map.put("year", year);
        map.put("month", month);
        map.put("day", day);
        //送给前端
        map.put("userInformation", userInformation);
        return "person/information";
    }

    /**
     * @author : Lcywings
     * @date : 2021/7/6 13:47
     * @acl : true
     * @description : 个人信息提交
     */
    @RequestMapping(value = "/modInformation", method = RequestMethod.POST)
    public String modInformation(
            HttpSession session, UserInformation userInformation, Map<String, Object> map) {
        personService.updatePerson(userInformation);
        return "redirect:/toInformation";
    }


    /**
     * @author : Lcywings
     * @date : 2021/7/6 13:47
     * @acl : true
     * @description : 抽离出来的头像单独提交
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String modInformation(@RequestParam("uploadFile") MultipartFile multipartFile,
                                 HttpSession session) {
        personService.uploadPic(multipartFile, userId, session);
        return "redirect:/toInformation";
    }

    /**
     * @author : Lcywings
     * @date : 2021/7/7 8:44
     * @acl : true
     * @description :安全设置界面
     */
    @RequestMapping("/toSafety")
    public String toSafety(Map<String, Object> map) {
        UserInformation userInformation = (UserInformation) personService.getPersonalAssets(userId).get("userInformation");
        map.put("userInformation", userInformation);
        return "person/safety";
    }

    /**
     * @author : Lcywings
     * @date : 2021/7/7 8:46
     * @acl : true
     * @description : 去往修改密码界面
     */
    @RequestMapping("/toPassword")
    public String toPassword(Map<String, Object> map) {
        map.put("userId", userId);
        return "person/password";
    }

    /**
     * @author : Lcywings
     * @date : 2021/7/7 8:46
     * @acl : true
     * @description : 修改密码界面
     */
    @RequestMapping("/modPassword")
    public String modPassword(Map<String, Object> map, HttpServletRequest request) {
        String password = request.getParameter("password");
        String password1 = request.getParameter("password1");
        String password2 = request.getParameter("password2");

        //比较两次新密码是否一致
        if (!personService.checkedPassword(password1, password2)) {
            map.put("errMsg", "两次新密码输入不一致");
            return "person/password";
        }
        //获得用户详情
        UserLogin userLogin = personService.selectUserLogin(Integer.valueOf(userId));
        //校验旧密码是否一致
        if (userLogin.getPassword().equals(EncodeUtils.testDigest(password))) {
            personService.updatePassword(Integer.valueOf(userId), EncodeUtils.testDigest(password1));
            map.put("errMsg", "修改成功");
        } else {
            map.put("errMsg", "旧密码错误");
            return "person/password";
        }
        return "person/password";
    }


    /**
     * @author : Lcywings
     * @date : 2021/7/7 8:46
     * @acl : true
     * @description : 去往修改地址界面
     */
    @RequestMapping("/toAddress")
    public String toAddress(Map<String, Object> map) {
        //获取用户信息
        UserInformation userInformation = (UserInformation) personService.getPersonalAssets(userId).get("userInformation");
        map.put("userInformation", userInformation);
        //获取地址信息
        List<ShopAddress> addrs = personService.getShopAddressByUserId(userId);

        map.put("addrs", addrs);
        map.put("addr", new ShopAddress());
        return "person/address";
    }

    /**
     * @author : Lcywings
     * @date : 2021/7/9 13:33
     * @acl : true
     * @description : 新增地址
     */
    @RequestMapping("/toAddAddress")
    public String addaddress(Map<String, Object> map, ShopAddress shopAddress) {

        shopAddress.setUserId(userId);
        shopAddress.setDefaultTag(1);
        personService.insertShopAddressByUserId(shopAddress);

        return "redirect:/toAddress";
    }

    /**
     * @author : Lcywings
     * @date : 2021/7/8 13:58
     * @acl : true
     * @description : 删除地址
     */
    @RequestMapping(value = "/deleteAddr", method = RequestMethod.POST)
    @ResponseBody
    public String deleteAddr(HttpServletRequest request) {
        //获取地址id
        String shopId = request.getParameter("shopId");
        //根据地址id删地址
        personService.deleteAddrByUserIdAndShopId(Integer.valueOf(shopId), userId);
        return "";
    }

    /**
     * @author : Lcywings
     * @date : 2021/7/9 16:28
     * @acl : true
     * @description : 设置默认地址
     */
    @RequestMapping(value = "/setDefShopId", method = RequestMethod.POST)
    @ResponseBody
    public String setDefShopId(HttpServletRequest request) {
        //获取默认地址id
        String defShopId = request.getParameter("defShopId");
        //根据默认地址id 设置默认
        personService.setDefShopIdByUserIdAndShopId(Integer.valueOf(defShopId), userId);
        return "";
    }

    /**
     * @author : Lcywings
     * @date : 2021/7/7 8:46
     * @acl : true
     * @description : 主页界面
     */
    @RequestMapping("/home")
    public String home() {
        return "home/home2";
    }

    /**
     * @author : Lcywings
     * @date : 2021/7/8 22:09
     * @acl : true
     * @description : 首页上方栏登录校验，判断是否显示欢迎用户
     */
    @RequestMapping("/checkLogin")
    @ResponseBody
    public String checkLogin(HttpSession session) {
        if (null == session.getAttribute("user") || "".equals(session.getAttribute("user")))
            return "0";
        else
            return "1";
    }

    /**
     * @author : Lcywings
     * @date : 2021/7/8 11:19
     * @acl : true
     * @description : 去往足迹页面
     */
    @RequestMapping("/toFoot")
    public String toFoot(Map<String, Object> map) {
        List<UserFootprint> userFootprints = personService.queryUserFootByUserId(userId);
        List<Product> products = new ArrayList<>();
        for (int i = 0; i < userFootprints.size(); i++) {
            products.add(personService.queryProductByproductId(userFootprints.get(i).getProductId()));
        }
        map.put("products", products);
        map.put("userFootprints", userFootprints);
        return "person/foot";
    }

    /**
     * @author : Lcywings
     * @date : 2021/7/8 13:58
     * @acl : true
     * @description : 删除足迹
     */
    @RequestMapping(value = "/deleteFoot", method = RequestMethod.POST)
    @ResponseBody
    public String deleteFoot(HttpServletRequest request) {
        String footPrintId = request.getParameter("footPrintId");
        personService.deleteFootByuserIdAnd(Integer.valueOf(footPrintId), userId);
        return "person/foot";
    }

    /**
     * @author : Lcywings
     * @date : 2021/7/8 15:13
     * @acl : true
     * @description : 去往收藏界面
     */
    @RequestMapping(value = "/toCollection")
    public String toCollection(Map<String, Object> map, HttpSession session) {
        if (verify(session)) {
            return "redirect:/doLogin";
        }
        List<UserCollection> userCollections = personService.queryUserCollectionByUserId(userId);
        List<Product> products = new ArrayList<>();
        for (int i = 0; i < userCollections.size(); i++) {
            products.add(personService.queryProductByproductId(userCollections.get(i).getProductId()));
        }
        map.put("products", products);
        map.put("userCollections", userCollections);
        return "person/collection";
    }

    /**
     * @author : Lcywings
     * @date : 2021/7/8 13:58
     * @acl : true
     * @description : 删除收藏
     */
    @RequestMapping(value = "/deleteColl", method = RequestMethod.POST)
    @ResponseBody
    public String deleteColl(HttpServletRequest request) {
        String collectionId = request.getParameter("collectionId");
        personService.deleteCollectionByUserIdAndCollectionId(Integer.valueOf(collectionId), userId);
        return "person/collection";
    }

    /**
     * @author : Lcywings
     * @date : 2021/7/8 19:05
     * @acl : true
     * @description : 去往订单界面
     */
    @RequestMapping("/toOrder")
    public String toOrder(Map<String, Object> map, HttpSession session) {
        if (verify(session)) {
            return "redirect:/doLogin";
        }
        List<OrderList> orderListsSort = new ArrayList<>();
        orderListsSort = personService.selectOrdersByUserId(userId);
        map.put("orderLists", orderListsSort);
        return "person/order";
    }

    /**
     * @author : Lcywings
     * @date : 2021/7/10 2:08
     * @acl : true
     * @description : 删除订单
     */
    @RequestMapping(value = "/deleteOrderNum", method = RequestMethod.POST)
    @ResponseBody
    public String deleteOrderNum(HttpServletRequest request) {
        String orderNum = request.getParameter("orderNum");
        personService.deleteOrderByuserIdAndOrderNum(orderNum, userId);
        return "";
    }


    /**
     * @author : Lcywings
     * @date : 2021/7/8 19:05
     * @acl : true
     * @description : 去往评论界面
     */
    @RequestMapping("/toComment")
    public String toComment(Map<String, Object> map) {
        //查询该用户所有评论
        map.put("comments", personService.queryCommentsByUserId(userId));
        //查询所有商品
        map.put("products", personService.queryProductByUserId());
        return "person/comment";
    }

    /**
     * @author : Lcywings
     * @date : 2021/7/8 19:05
     * @acl : true
     * @description : 去往咨询界面
     */
    @RequestMapping("/toConsultation")
    public String toConsultation() {
        return "person/consultation";
    }

    /**
     * @author : Lcywings
     * @date : 2021/7/8 19:05
     * @acl : true
     * @description : 去往反馈界面
     */
    @RequestMapping("/toSuggest")
    public String toSuggest() {
        return "person/suggest";
    }


    /**
     * @author : Lcywings
     * @date : 2021/7/10 16:39
     * @acl : true
     * @description : 退出登录
     */
    @RequestMapping("/exit")
    public String exit(HttpSession session) {
        session.removeAttribute("user");
        return "home/login";
    }

}
